<template>
  <d2-container>

    <template slot="header">
      <el-form :gutter="24" ref="search-box" :model="mainQuery"  label-position="left" :inline="true" label-width="90px" v-show="showSearchBox">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="商户号：" size="mini">
              <el-input placeholder="" v-model="mainQuery.mchNo" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
            </el-form-item>    
          </el-col>

          <el-col :span="8">
            <el-form-item label="终端号：" size="mini">
              <el-input placeholder="" v-model="mainQuery.terNo" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="订单号：" size="mini">
              <el-input placeholder="" v-model="mainQuery.tradeNo" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="勾兑状态：" size="mini">
              <el-select v-model="mainQuery.isChecked" size="small" clearable>
                <el-option
                  v-for="item in isCheckedOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="退款状态：" size="mini">
              <el-select v-model="mainQuery.isRefund" size="small" clearable>
                <el-option
                  v-for="item in isRefundOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="结算状态：" size="mini">
              <el-select v-model="mainQuery.isSettle" size="small" clearable>
                <el-option
                  v-for="item in isSettleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="发货状态：" size="mini">
              <el-select v-model="mainQuery.isShip" size="small" clearable>
                <el-option
                  v-for="item in isShipOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="冻结状态：" size="mini">
              <el-select v-model="mainQuery.isFrozen" size="small" clearable>
                <el-option
                  v-for="item in isFrozenOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="解冻状态：" size="mini">
              <el-select v-model="mainQuery.isThaw" size="small" clearable>
                <el-option
                  v-for="item in isThawOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="拒付状态：" size="mini">
              <el-select v-model="mainQuery.isDis" size="small" clearable>
                <el-option
                  v-for="item in isDisOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="通道：" size="mini">
              <el-select v-model="mainQuery.channelId" size="small" clearable>
                <el-option
                  v-for="item in channelIdOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="测试单：" size="mini">
              <el-select v-model="mainQuery.isTest" size="small" clearable>
                <el-option
                  v-for="item in isTestOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="邮箱：" size="mini">
              <el-input placeholder="" v-model="mainQuery.cardEmail" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="IP：" size="mini">
              <el-input placeholder="" v-model="mainQuery.ipAddress" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="电话：" size="mini">
              <el-input placeholder="" v-model="mainQuery.cardFullPhone" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="姓名：" size="mini">
              <el-input placeholder="" v-model="mainQuery.cardFullName" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="手工结算：" size="mini">
              <el-select v-model="mainQuery.needHandSettle" size="small" clearable>
                <el-option
                  v-for="item in needHandSettleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="时间区间：" size="mini">
          <el-date-picker
            size="small" 
            v-model="dateTimeRange"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="datetimePickerOptions"
            @change="onDateTimePickerChange"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <div class="search-btn-box">
        <div class="right">
          <el-button class="filter-item" icon="el-icon-download" size="small" @click="handleExportExcel">导出</el-button>
          <el-button class="filter-item" icon="el-icon-s-check" type="success" @click="handleHandSettle" :loading="mainTable.loading" size="small" v-if="$options.filters['checkButtonAccess']('handsettle-add')">手动结算</el-button>
          <el-button class="filter-item" icon="" type="default" @click="resetMainData" :loading="mainTable.loading" size="small">重置</el-button>
          <el-button class="filter-item" icon="el-icon-search" type="primary" @click="handleSearch" :loading="mainTable.loading" size="small">查询</el-button>
        </div>
        <el-link type="primary" @click="showSearchBox = !showSearchBox">{{ showSearchBox ? '收起' : '展开' }}</el-link>
      </div>
    </template>

    <!--主列表数据-->
    <d2-crud
      ref="d2Crud"
      selection-row
      :options="mainTable.options"
      :index-row="mainTable.indexRow"
      :columns="mainTable.columns"
      :data="mainTable.list"
      :loading="mainTable.loading"
      :rowHandle="mainTable.rowHandle"
      @current-change="onMainCurrentChange"
      @custom-emit-handle-order="handleOrderDetail"
      @custom-emit-handle-email="handleEmail"
      @selection-change="onMainSelectionChange"
    ></d2-crud>

    <template slot="footer">
      <el-pagination
        @size-change="handleMainSizeChange"
        @current-change="handleMainPageChange"
        :current-page="mainTable.pagination.currentPage"
        :page-sizes="mainTable.pagination.pageSizes"
        :page-size="mainTable.pagination.pageSize"
        :page-count="mainTable.pagination.pageCount"
        :total="mainTable.pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        :background="true"
        >
      </el-pagination>
    </template>

    <!-- <dialog-detail ref="dialog-detail" @dialog-close="fetchMainData"></dialog-detail> -->

    <dialog-email ref="dialog-email" @dialog-close="fetchMainData"></dialog-email>

    <common-export ref="common-export"></common-export>

  </d2-container>
</template>

<script>

import ApiMain from '@/api/trade.detail';
// import DialogAdd from './dialog-add';
import CommonExport from '../../common/export';
import DialogEmail from '../detail/dialog-email';
import util from '@/libs/util.js';
import ChannelApiMain from '@/api/bank.channel';
import HandSettleApiMain from '@/api/trade.hand';
import { isCheckedOptions, isRefundOptions, isFrozenOptions, isShipOptions, isSettleOptions, isDisOptions, isThawOptions, isTestOptions, needHandSettleOptions } from '@/const/constant';
import DatetimePickerMixin from '@/mixin/DatetimePickerMixin'


export default {
  name: 'trade-staffDetail',
  mixins: [
    DatetimePickerMixin,
  ],
  components: {
    // 'dialog-detail': DialogAdd,
    'dialog-email': DialogEmail,
    'common-export': CommonExport,
  },
  data () {
    return {

      mainQuery: {
        mchNo: '',
        terNo: '',
        tradeNo: '',
        isRefund: '',
        isChecked: '',
        isSettle: '',
        isShip: '',
        isDis: '',
        isFrozen: '',
        isThaw: '',
        channelId: '',
        cardType: '',
        transStatus: '',
        cardEmail: '',
        cardFullName: '',
        cardFullPhone: '',
        ipAddress: '',
        needHandSettle: '',
        startTime: '',
        endTime: ''
      },

      mainTable: {
        loading: false,
        options: {
          border             : true,
          stripe             : true,
          highlightCurrentRow: true,
          emptyText          : '暂无数据',
          size               : 'mini',
        },
        // indexRow: {
        //   title:'序号',
        //   width: "80",
        //   align:'center'
        // },
        indexRow: null,
        allowSelect: false,
        columns: [
          // {title: 'id', key: 'id', align: 'center', showOverflowTooltip: true},
          {title: '单号', key: 'tradeNo', align: 'center', width: '180', showOverflowTooltip: true, fixed: true},
          {title: '商户单号', key: 'orderNo', align: 'center', width: '180', showOverflowTooltip: true},
          {title: '商户号', key: 'mchNo', align: 'center', width: '120', showOverflowTooltip: true},
          {title: '终端号', key: 'terNo', align: 'center', width: '120', showOverflowTooltip: true},
          {title: '交易时间', key: 'createTime', align: 'center', width: '180', showOverflowTooltip: true},
          {title: '交易金额', key: 'mchTransAmount', align: 'center', width: '120', showOverflowTooltip: true, formatter(row, column, cellValue, index) {
            return row.mchTransCurrency + ' ' + row.mchTransAmount / 100
          }},
          {title: '交易状态', key: 'strTransStatus', align: 'center', width: '120', showOverflowTooltip: true},
          {title: '银行交易单号', key: 'relNo', align: 'center', width: '180', showOverflowTooltip: true},
          // {title: '银行交易金额', key: 'bankTransAmount', align: 'center', width: '120', showOverflowTooltip: true, formatter(row, column, cellValue, index) {
          //   return row.bankCurrency + ' ' + row.bankTransAmount / 100
          // }},
          // {title: '商户结算金额', key: 'settleAmount', align: 'center', width: '120', showOverflowTooltip: true, formatter(row, column, cellValue, index) {
          //   return row.settleCurrency + ' ' + row.settleAmount / 100
          // }},
          {title: '卡种', key: 'cardType', align: 'center', showOverflowTooltip: true},
          {title: '卡号', key: 'cardNo', align: 'center', width: '180', showOverflowTooltip: true},
          {title: 'IP', key: 'ipAddress', align: 'center', width: '180', showOverflowTooltip: true},
          {title: '邮箱', key: 'cardEmail', align: 'center', width: '180', showOverflowTooltip: true},
          {title: '交易通道', key: 'channelName', align: 'center', width: '180', showOverflowTooltip: true},
          {title: '是否勾兑', key: 'strIsChecked', align: 'center', showOverflowTooltip: true},
          {title: '结算状态', key: 'strIsSettle', align: 'center', showOverflowTooltip: true},
        ],
        rowHandle: {
          width: '250',
          align: 'center',
          fixed: 'right',
          custom: [
            // {
            //   text: '查看订单',
            //   type: 'primary',
            //   size: 'mini',
            //   emit: 'custom-emit-handle-order'
            // },
            {
              text: '邮箱发送详情',
              type: 'default',
              size: 'mini',
              emit: 'custom-emit-handle-email'
            }
          ]
        },
        list: [],
        pagination: {
          currentPage: 1,
          pageSize   : 50,
          total      : 0,
          pageSizes  : [50, 100, 200]
        },
        selectionRow: [],
      },

      isCheckedOptions: isCheckedOptions,
      isRefundOptions: isRefundOptions,
      isFrozenOptions: isFrozenOptions,
      isShipOptions: isShipOptions,
      isSettleOptions: isSettleOptions,
      isDisOptions: isDisOptions,
      isThawOptions: isThawOptions,
      isTestOptions: isTestOptions,
      needHandSettleOptions: needHandSettleOptions,
      channelIdOptions: [],
      dateTimeRange: [],
      showSearchBox: false,
      fullLoading: true,
      tExportLog: null,
    }
  },
  mounted () {
    this.fetchChannelOptions();
    this.resetMainData();
  },
  beforeDestroy () {
  },
  methods: {

    handleSearch () {
      this.mainTable.pagination.currentPage = 1;
      this.fetchMainData();
    },

    renderMainData (re) {
      this.mainTable.list = re.list;
      this.mainTable.pagination.total = re.total;
    },

    handleMainSizeChange (val) {
      this.mainTable.pagination.pageSize = val;
      this.mainTable.pagination.currentPage = 1;
      this.fetchMainData()
    },
    handleMainPageChange (val) {
      this.mainTable.pagination.currentPage = val;
      this.fetchMainData()
    },

    buildMainQuery () {

      var query = {
        page  : this.mainTable.pagination.currentPage,
        limit : this.mainTable.pagination.pageSize,
        search: this.mainQuery,
      };

      return query;
    },

    resetMainData () {

      this.mainQuery = {
        mchNo: '',
        terNo: '',
        tradeNo: '',
        isRefund: '',
        isChecked: '',
        isSettle: '',
        isShip: '',
        isDis: '',
        isFrozen: '',
        isThaw: '',
        channelId: '',
        cardType: '',
        transStatus: '',
        cardEmail: '',
        cardFullName: '',
        cardFullPhone: '',
        ipAddress: '',
        needHandSettle: '',
        startTime: '',
        endTime: ''
      };

      this.fetchMainData();
    },

    fetchChannelOptions () {
      ChannelApiMain.option().then(re => {
        this.channelIdOptions = re;
      })
    },

    async fetchMainData () {

      this.mainTable.loading = true;

      try {
        var re = await ApiMain.list(this.buildMainQuery());
        this.renderMainData(re);
      } catch (err) {}

      this.mainTable.loading = false;

    },

    onDateTimePickerChange() {
      this.mainQuery.startTime = this.dateTimeRange && this.dateTimeRange.length > 0 ? this.dateTimeRange[0] : ''
      this.mainQuery.endTime = this.dateTimeRange && this.dateTimeRange.length > 0 ? this.dateTimeRange[1] : ''
    },

    onMainCurrentChange (now, old) {
      this.mainTable.current = now;
    },

    onMainDoubleClick (now) {
      this.mainTable.current = now;
      this.handleSet();
    },

    onMainSelectionChange (now, old) {
      this.mainTable.selectionRow = now
    },

    handleOrderDetail ({index, row}) {
      this.$refs['dialog-detail'].show(row.id);
    },

    handleEmail ({index, row}) {
      this.$refs['dialog-email'].show(row.id);
    },

    handleExportExcel () {
      this.$refs['common-export'].handleExportExcel(ApiMain, this.mainQuery);
    },

    // 手动结算
    handleHandSettle () {
      if (this.mainTable.selectionRow.length == 0) {
        this.$message({message: '请选择行', type: 'error'});
        return;
      }

      // 检查是否符合条件
      let tradeNos = [];
      for (var i in this.mainTable.selectionRow) {
        if (this.mainTable.selectionRow[i].isSettle != 0) {
          this.$message({message: '单号：' + this.mainTable.selectionRow[i].tradeNo + '结算状态不是未结算，不能操作', type: 'error'});
          return;
        }
        if (this.mainTable.selectionRow[i].currentTimeStamp - this.mainTable.selectionRow[i].createTimeStamp < this.mainTable.selectionRow[i].handSettleLimit) {
          this.$message({message: '单号：' + this.mainTable.selectionRow[i].tradeNo + '不符合手工结算条件' + (this.mainTable.selectionRow[i].handSettleLimit / 24 / 3600) + '天', type: 'error'});
          return;
        }
        tradeNos.push(this.mainTable.selectionRow[i].tradeNo);
      }

      this.$confirm('确定对选中的订单进行手动结算操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doHandSettle(tradeNos)
      });
    },

    async doHandSettle (tradeNos) {
      await HandSettleApiMain.add({ tradeNos: tradeNos });
      this.$message({message: '操作成功', type: 'success'});
      this.fetchMainData();
    }

  }
}
</script>

<style>

</style>
